<template>
    <div class="main-container">
        <div class="patient-selection">
            <h3 class="h3-1">请选择患者信息</h3>
            <p>以便医生给出准确的治疗建议，患者信息仅医生可见</p>

            <div class="patient-list">
                <div v-for="(patient, index) in patients" :key="index"
                    :class="['patient-card', { selected: selectedPatient === index }]" @click="selectPatient(index)">
                    <div class="card-header">
                        <!-- 添加头像 -->
                        <img class="patient-avatar" :src="patient.gender === 0 ? maleAvatar : femaleAvatar"
                            alt="患者头像" />
                        <div class="patient-name-and-edit">
                            <h4 class="patient-name">{{ patient.name }}</h4>
                            <!-- 动态生成编辑链接 -->
                            <a class="edit-button" :href="`/to_editor/${patient.id}`">编辑</a>
                        </div>
                    </div>
                    <p class="patient-info">
                        {{ patient.get_gender_display }} {{ calculateAge(patient.birth) }}岁 {{ patient.weight }}kg
                    </p>

                    <!-- 仅选中的患者展示详细内容 -->
                    <div v-if="selectedPatient === index">
                        <hr>
                        <p class="patient-details">
                            肝肾功能:
                            &nbsp;
                            <span v-if="patient.is_liver">肝功能正常</span>
                            <span v-else style="color: red;">肝功能异常</span>
                            &nbsp;
                            <span v-if="patient.is_kidney">肾功能正常</span>
                            <span v-else style="color: red;">肾功能异常</span>
                        </p>
                        <p class="patient-details">
                            过敏史:
                            &nbsp;
                            <span v-if="!patient.is_allergy">无</span>
                            <span v-else>{{ patient.allergy }}</span>
                        </p>
                        <p class="patient-details">
                            过往病史:
                            &nbsp;
                            <span v-if="!patient.is_history">无</span>
                            <span v-else>{{ patient.history }}</span>
                        </p>
                    </div>
                </div>
            </div>

            <div @click="addPatient" class="add-patient">
                <p class="add-patient-item">+</p>
                <p class="add-patient-item">添加患者</p>
            </div>
            <button @click="submitSelection" :disabled="selectedPatient === null">提交</button>
        </div>
    </div>
</template>



<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";

const router = useRouter();
const patients = ref([]);
const selectedPatient = ref(null);

// 定义头像资源路径
const maleAvatar = "https://img1.dxycdn.com/2021/0906/653/9705846928756232053-22.png"; // 替换为实际的男性头像图片路径
const femaleAvatar = "https://img1.dxycdn.com/2021/0906/719/0474375158436232053-22.png"; // 替换为实际的女性头像图片路径

// Fetch patients from the backend
const fetchPatients = async () => {
    try {
        const response = await axios.get("http://127.0.0.1:8000/patient/patient/", {
            headers: {
                "Content-Type": "application/json",
                Authorization: `Bearer ${localStorage.getItem("token")}`,  // 修改这里为 'Bearer'
            },
        });
        


        patients.value = response.data;
    } catch (error) {
        console.error("Error fetching patients:", error);
    }
};

// Handle selecting a patient
const selectPatient = (index) => {
    selectedPatient.value = index;
};

// Navigate to the patient creation page
const addPatient = () => {
    window.location.href = "/to_add";
};

// Submit the selected patient
const submitSelection = () => {
    if (selectedPatient.value !== null) {
        try {
            const selectedPatientData = patients.value[selectedPatient.value].id;

            console.log(selectedPatientData);
            localStorage.removeItem("PatientId");
            localStorage.setItem("PatientId", selectedPatientData);
            localStorage.removeItem("selectedCoupon");
            router.push("/pay");
        } catch (error) {
            console.error("Error submitting selection:", error);
        }
    }
};

const calculateAge = (birthDate) => {
    const birth = new Date(birthDate); // 将出生日期转换为 Date 对象
    const today = new Date(); // 获取今天的日期
    let age = today.getFullYear() - birth.getFullYear(); // 计算年份差
    const m = today.getMonth() - birth.getMonth(); // 计算月份差
    // 如果当前月份早于出生月份，或者是同月但今天还没过生日，则减去 1 年
    if (m < 0 || (m === 0 && today.getDate() < birth.getDate())) {
        age--;
    }
    return age;
};

// Fetch patients when the component is mounted
onMounted(() => {
    fetchPatients().then(() => {
        if (patients.value.length > 0) {
            selectedPatient.value = 0; // 默认选中第一个患者
        }
    });
});
</script>


<style scoped>
.main-container {
    max-width: 1000px;
    margin: 0 auto;
    min-height: 100vh;
    background-color: #f7f8fa;
    padding: 20px;
    padding-bottom: 70px;
    position: relative;
    box-shadow: 0 3px 3px rgba(0, 0, 0, 0.3);
}

.h3-1 {
    margin-top: 2px;
    font-size: 29px;
}

.patient-selection {
    font-family: Arial, sans-serif;
}

.patient-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
    margin-right: 10px;
}

.card-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.patient-name-and-edit {
    flex: 1;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.patient-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.patient-card {
    border: 1px solid #ddd;
    padding: 15px;
    border-radius: 15px;
    cursor: pointer;
    background-color: #fff;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.patient-card.selected {
    border-color: #42b983;
    background-color: #f0f9f5;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;
}

.patient-name {
    font-size: 18px;
    font-weight: bold;
    margin: 0;
}

.edit-button {
    font-size: 14px;
    color: #42b983;
    cursor: pointer;
    text-decoration: none;
}

.patient-info {
    font-size: 16px;
    color: #333;
    margin: 5px 0;

}

.patient-details {
    font-size: 14px;
    color: #666;
    margin: 2px 0;
}

.add-patient{
    background-color: #eaeaea;
    margin-top: 10px;
    width: 100%;
    height: 80px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    cursor: pointer;
    border-radius: 10px;
}

.add-patient-item {
    /* 假设这是子元素的类名 */
    margin-top: 5px;
    /* 调整这个值来缩短间距 */
    margin-bottom: 5px;
    /* 调整这个值来缩短间距 */
    color: #42b983;
}

/* 第一个子元素不需要上边距 */
.add-patient-item:first-child {
    margin-top: 0;
}

/* 最后一个子元素不需要下边距 */
.add-patient-item:last-child {
    margin-bottom: 0;
}

/* 提交按钮的固定定位 */
button {

    /* transform: matrix(-50%);
    left:50%; */
    position: fixed;
    
    /* 固定定位 */
    margin-left: 3%;
    bottom: 15px;
    /* 固定在底部 */
    width: 50%;
    /* 按钮宽度充满全屏 */
    padding: 10px;
    background-color: #42b983;
    color: #fff;
    border: none;
    border-radius: 50px;
    cursor: pointer;
    box-sizing: border-box;
    /* 确保边距和填充不影响按钮尺寸 */
}

button:disabled {
    background-color: #ddd;
    cursor: not-allowed;
}
</style>
